<template>
  <el-card class="box-card" style="width: 826px">
    <template #header>
      <div class="card-header">
        <span>自定义数据</span>
        <span>
          <el-button type="primary" size="small" link @click="useNewData">
            <el-icon><CirclePlusFilled /></el-icon>
            <span>新建空白数据</span>
          </el-button>
          <el-button
            type="primary"
            size="small"
            link
            @click="usePresent"
            :disabled="!flowStore.rawData || flowStore.rawData.length == 0"
          >
            <el-icon><Link /></el-icon>
            <span>使用当前数据</span>
          </el-button>
          <el-popover placement="bottom" :width="180" trigger="click">
            <template #reference>
              <el-button type="primary" size="small" link>
                <el-icon><Download /></el-icon>
                <span>使用历史数据</span>
              </el-button>
            </template>
            <div
              style="display: flex; flex-direction: column; align-items: center"
            >
              <div>历史数据日期</div>
              <div>
                <el-date-picker
                  v-model="formData.historyDate"
                  type="date"
                  placeholder=""
                  format="YYYY-MM-DD"
                  style="width: 160px"
                  size="small"
                />
              </div>
              <div>
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handlePreview"
                  >查看</el-button
                >
                <el-button type="primary" link size="small" @click="useHistory"
                  >使用</el-button
                >
              </div>
            </div>
          </el-popover>
          <el-popover placement="bottom" :width="180" trigger="click">
            <template #reference>
              <el-button type="primary" size="small" link>
                <el-icon><Box /></el-icon>
                <span>使用存档文件</span>
              </el-button>
            </template>
            <div style="text-align: center; padding: 6px 0">
              <el-button type="primary" size="small" @click="saveFile">
                <span>保存为JSON文件</span>
              </el-button>
            </div>
            <div style="text-align: center; padding: 6px 0">
              <el-upload action="" :on-change="loadFile" :auto-upload="false">
                <el-button type="primary" size="small">
                  <span>读取JSON文件</span>
                </el-button>
              </el-upload>
            </div>
          </el-popover>
          <el-button
            :type="flowStore.loaderType == 'manual' ? 'success' : 'primary'"
            size="small"
            :disabled="!valid"
            @click="handleLoad"
          >
            <span>{{
              flowStore.loaderType == "manual" ? "已加载" : "加载"
            }}</span>
          </el-button>
        </span>
      </div>
    </template>
    <div v-if="formData.content.length > 0">
      <div class="errortip" v-if="!valid">
        错误: 进入量不能全为 0 或小于 0 !
      </div>
      <div class="scrolltip">提示: 按住 Shift 再滚动鼠标滚轮, 可横向滚动</div>
      <el-scrollbar class="scrollbar-flex-content">
        <el-space :size="16">
          <div
            v-for="(momentData, momentIndex) in formData.content"
            :key="'moment_' + momentIndex"
            class="scrollbar-demo-item"
          >
            <div style="padding: 18px 0 6px 0">
              {{
                dayjs(formData.begTime)
                  .add(momentIndex * 15, "minute")
                  .format("HH:mm")
              }}
              至
              {{
                dayjs(formData.begTime)
                  .add((momentIndex + 1) * 15, "minute")
                  .format("HH:mm")
              }}
            </div>
            <div v-for="(tag, tagIndex) in tags" class="tag-data-item">
              <span style="display: inline-block; width: 110px">
                {{ tag }}
              </span>
              <input
                type="number"
                v-model="momentData[tagIndex]"
                style="width: 40px"
              />
            </div>
          </div>
        </el-space>
      </el-scrollbar>
    </div>
    <ReferanceViewer ref="referanceViewer" />
  </el-card>
</template>

<script setup>
import { h, ref, computed, onMounted } from "vue";
import useFlowStore from "@/store/flow.js";
import dayjs from "dayjs";
import loadData from "./utils/loader.js";
import ReferanceViewer from "./ReferanceViewer.vue";
import FileSaver from "file-saver";
import airportArrange from "../utils/arrange.js";
import summary from "../utils/summary.js";
import { ElMessageBox, ElNotification } from "element-plus";

const referanceViewer = ref();

const flowStore = useFlowStore();
const formData = flowStore.loaderConfig.manual;
const tags = computed(() => flowStore.tags);

const range = computed(() => {
  let start = dayjs(formData.historyDate).format("YYYY-MM-DD") + " 04:00:00";
  let end =
    dayjs(formData.historyDate).add(1, "day").format("YYYY-MM-DD") +
    " 04:00:00";
  return { start, end };
});

const handlePreview = () => {
  loadData(range.value, false).then((res) => {
    referanceViewer.value.open(res);
  });
};

const valid = computed(() => {
  for (let i = 0; i < formData.content.length; i++) {
    for (let j = 0; j < formData.content[i].length; j++) {
      if (formData.content[i][j] > 0) {
        return true;
      } else if (formData.content[i][j] < 0) {
        return false;
      }
    }
  }
  return false;
});

const setBegtime = () => {
  let daytime = dayjs().year(2077).month(10).day(3).hour(4).minute(0).second(0);
  let begTime = daytime.format("YYYY-MM-DD HH:mm:ss");
  formData.begTime = begTime;
};
const usePresent = () => {
  setBegtime();
  formData.content = JSON.parse(JSON.stringify(flowStore.rawData));
};

const useHistory = () => {
  setBegtime();
  formData.content.length = 0;
  loadData(range.value, false).then((res) => {
    formData.content = res.rawData;
  });
};

const useNewData = () => {
  setBegtime();
  let content = new Array();
  let tagsArray = tags.value;
  for (let i = 0; i < 96; i++) {
    let lineArray = new Array();
    for (let j = 0; j < tagsArray.length; j++) {
      lineArray.push(0);
    }
    content.push(lineArray);
  }
  formData.content = content;
};

const handleLoad = () => {
  flowStore.loaderType = "manual";
  flowStore.autoRefresh = false;
  flowStore.ignoreWarning = true;
  flowStore.rawData = formData.content;
  flowStore.begTime = formData.begTime;
  let data = summary(flowStore.rawData, flowStore.tags);
  console.log(data);
  ElNotification({
    type: "success",
    position: "bottom-right",
    duration: 10000,
    title: "自定义数据",
    message: h("div", null, [
      h(
        "div",
        null,
        [
          h("b", null, "ZUUU"),
          h(
            "span",
            { style: "padding:0 12px" },
            `${data.airport.ZUUU.type.DEP}起`
          ),
          h("span", null, `${data.airport.ZUUU.type.ARR}落`),
        ]
      ),
      h(
        "div",
        null,
        [
          h("b", null, "ZUTF"),
          h(
            "span",
            { style: "padding:0 12px" },
            `${data.airport.ZUTF.type.DEP}起`
          ),
          h("span", null, `${data.airport.ZUTF.type.ARR}落`),
        ]
      ),
      h(
        "div",
        null,
        [
          h("b", null, "ZUMY"),
          h(
            "span",
            { style: "padding:0 12px" },
            `${data.airport.ZUMY.type.DEP}起`
          ),
          h("span", null, `${data.airport.ZUMY.type.ARR}落`),
        ]
      ),
    ]),
  });
};

const saveFile = () => {
  let data = JSON.stringify(flowStore.loaderConfig.manual.content);
  let blob = new Blob([data], { type: "application/json" });
  FileSaver.saveAs(
    blob,
    `流量数据生存档${dayjs().format("YYYYMMDDHHmmss")}.json`
  );
};

const loadFile = (file) => {
  let reader = new FileReader(); //先new 一个读文件的对象 FileReader
  if (typeof FileReader === "undefined") {
    //用来判断你的浏览器是否支持 FileReader
    this.$message({
      type: "info",
      message: "您的浏览器不支持文件读取。",
    });
    return;
  }
  reader.readAsArrayBuffer(file.raw); //读任意文件
  reader.onload = function (e) {
    let ints = new Uint8Array(e.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
    // ints = ints.slice(0, 5000); //截取一段读取的内容
    let snippets = new TextDecoder("gb2312").decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
    // console.log("读取的内容如下：");
    // console.log(snippets);
    formData.content = JSON.parse(snippets);
  };
};

onMounted(() => {
  if (formData.content.length == 0) {
    setTimeout(() => useNewData(), 250);
  }
  if (formData.historyDate == "") {
    formData.historyDate = new Date();
  }
});
</script>

<style scoped>
@import "./styles/card.css";

.scrollbar-flex-content {
  display: flex;
  padding-bottom: 24px;
}
.scrollbar-demo-item {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-info-light-9);
  color: var(--el-color-info);
}
.tag-data-item {
  font-family: Consolas, monospace;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
}

.scrolltip {
  font-size: 12px;
  background: var(--el-color-info-light-9);
  color: var(--el-color-info);
  margin: 16px 0;
  padding: 4px 12px;
  border-radius: 4px;
}

.errortip {
  font-size: 12px;
  background: var(--el-color-danger-light-9);
  color: var(--el-color-danger);
  margin: 16px 0;
  padding: 4px 12px;
  border-radius: 4px;
}
</style>
